import store from "../store";
import type { CartItem } from '../store';
import { addItemsToCartAsync, getItemsFromCartAsync } from "../api/cart";
import { getToken } from "./token";

const updateStorage = (items: CartItem[]) => {
  window.localStorage.removeItem('cart');
  if (items) {
    window.localStorage.setItem('cart', JSON.stringify(items));
    const token = getToken();
    if (token) addItemsToCartAsync(items, token);
  }
};

const populateCartWithStorage = (): void => {
  const setStore = (items: CartItem[]) => {
    const cart = store.state.cart;
    
    cart.length = 0;
    cart.push(...items);
  };
  const token = getToken();
  if (!token) return;
  getItemsFromCartAsync(token)
    .then(res => {
      if (res.data) {
        const data = JSON.parse(res.data) as CartItem[];
        setStore(data);
      }
    })
    .catch(err => {
      console.error(err);
      const v = window.localStorage.getItem('cart');
      if (v) {
        const cartInStorage = JSON.parse(v) as CartItem[];
        setStore(cartInStorage);
      }
    });
};

const addItemToCart = (item: CartItem): void => {
  store.setCartAction(item);
  updateStorage(store.state.cart);
};

const modifyItemInCart = (item: CartItem): void => {
  const cartItem = store.getCartItemAction(item);
  if (cartItem == null) throw new Error(`no such item in cart, storeId: ${item.storeId}, productId: ${item.productId}, attributeId: ${item.attributeId}`);
  Object.assign(cartItem, item);
  updateStorage(store.state.cart);
};

const removeItemFromCart = (o: { storeId: number; productId: number; attributeId: number }): ReturnType<typeof store['deleteCartItemAction']> => {
  const removedItem = store.deleteCartItemAction(o);
  updateStorage(store.state.cart);
  return removedItem;
};

const clearCartItem = (): void => {
  store.clearCartAction();
  updateStorage(store.state.cart);
};

const getCartItems = (): typeof store['state']['cart'] => {
  return store.state.cart;
};

const setCheckedCart = (items: CartItem[]): void => {
  window.localStorage.removeItem('checkedCart');
  if (items) window.localStorage.setItem('checkedCart', JSON.stringify(items));
};

const getCheckedCart = (): CartItem[] => {
  const v = window.localStorage.getItem('checkedCart');
  if (v) return JSON.parse(v) as CartItem[];
  return [];
};

export {
  addItemToCart,
  modifyItemInCart,
  removeItemFromCart,
  clearCartItem,
  getCartItems,

  populateCartWithStorage,

  setCheckedCart,
  getCheckedCart
}